package ar.com.tallerdos.smartdinner.sync;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.TextView;
import ar.com.tallerdos.smartdinner.R;
import ar.com.tallerdos.smartdinner.activity.ComidasLista;
import ar.com.tallerdos.smartdinner.activity.LoginActivity;
import ar.com.tallerdos.smartdinner.model.Usuario;
import ar.com.tallerdos.smartdinner.util.UsrManager;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

public class SincronizadorLogin extends AsyncTask<Void, Void, Void> {
	
	private static final String LOGIN_SERVICE = "consultarLogin.php";
	private static boolean initialSync = false;
	private static boolean checkBackGround = false;
	private List<Usuario> usuarios;
	private static LoginActivity context;
	
	ProgressDialog pdLoading;
	LoginActivity activity;
		
	public SincronizadorLogin(LoginActivity mainActivity) {
		activity = mainActivity;
		if(!checkBackGround){
		    pdLoading = new ProgressDialog(mainActivity);
		}
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();

		// this method will be running on UI thread
		if(!checkBackGround){
		    pdLoading.setMessage("\tLoading...");
		    pdLoading.show();
		}
	}

	@Override
	protected Void doInBackground(Void... params) {
		
		String usuariosJson = llamarWebService(Tarea.SERVER_URL + "/" + LOGIN_SERVICE);
		try {
			Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
			
			usuarios =  gson.fromJson(usuariosJson, new TypeToken<List<Usuario>>(){}.getType());
			if (usuarios == null) {
			    usuarios = new ArrayList<Usuario>();
			}
			
		    
		} catch (Exception e) { 
		    usuarios = new ArrayList<Usuario>();
		}
		return null;
	}


	@Override
	protected void onPostExecute(Void result) {
		// this method will be running on UI thread
		super.onPostExecute(result);
		pdLoading.dismiss();
		
		if(usuarios.size() > 0){
			TextView message = (TextView) context.findViewById(R.id.errorMsg);
			message.setVisibility(TextView.INVISIBLE);
			
			Intent intent = new Intent(context, ComidasLista.class);
			context.startActivity(intent);
			
			UsrManager.getInstance().setUsuario((Usuario) usuarios.toArray()[0]);
		}
		else{
			TextView message = (TextView) context.findViewById(R.id.errorMsg);
			message.setVisibility(TextView.VISIBLE);
		}
	}

	private String llamarWebService(String url) {
		InputStream is = null;

		try {
			
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
			nameValuePairs.add(new BasicNameValuePair("username",LoginActivity.getUsuario()));
			nameValuePairs.add(new BasicNameValuePair("password",LoginActivity.getPassword()));
			nameValuePairs.add(new BasicNameValuePair("cargo",LoginActivity.getLoginTipo().toString()));
			
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(url);
			
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
			Log.e("log_tag", "Conexion exitosa");
		} catch (Exception e) {
			Log.e("log_tag", "Error en conexion http" + e.toString());
		}

		return convertToString(is);
	}

	public String convertToString(InputStream is) {
		// convert response to string
		String result = "";

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();

			result = sb.toString();
			Log.e("log_tag",
					"Conversion Exitosa del resultado" + result.toString());
		} catch (Exception e) {
			Log.e("log_tag",
					"Error en conversion del resultado " + e.toString());
		}

		return result;
	}
	
	public static void setBackGroundCheck(){
		checkBackGround = true;
	}
	
	public static boolean getInitialSync(){
		return initialSync;
	}
	
	public static void setContext(LoginActivity contextActivity){
		context = contextActivity;
	}
}
